package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollectionUtil;
import com.tanhua.dubbo.api.mongo.SearchApi;
import com.tanhua.model.mongo.UserLocation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;


import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@DubboService
public class SearchApiImpl implements SearchApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 搜索附近的人
     *
     * @param distance
     * @return
     */
    @Override
    public List<Long> findSearch(Long userId, Long distance) {

        List<Long> locationUser = new ArrayList<>();
        Query query = new Query(Criteria.where("userId").is(userId));
        UserLocation location = mongoTemplate.findOne(query, UserLocation.class);
        if (location == null) {
            return locationUser;
        }
        Circle circle = new Circle(location.getLocation(), new Distance(distance / 1000, Metrics.KILOMETERS));
        Query locationQuery = new Query(Criteria.where("userId").ne(userId).and("location").withinSphere(circle));
        List<UserLocation> locationList = mongoTemplate.find(locationQuery, UserLocation.class);
        if (CollectionUtil.isNotEmpty(locationList)) {
            locationUser = locationList.stream().map(UserLocation::getUserId).collect(Collectors.toList());

        }
        return locationUser;
    }
}
